import {uEditUserPhone, uSelectUserInfo, verifyGetCode} from '@/api/user'
import {getStorage} from '@/utils/localstoreage'
import Taro from '@tarojs/taro'
import {observable, computed, action} from 'mobx'
import {createContext} from 'react'

class Edituserphone {
  @observable pageData: {
    devCount: number
    user: UserSetting.UserInfo | null
  } = {
    devCount: 0,
    user: null
  }
  @action.bound
  async updatePageDataSource() {
    let userId = getStorage('userId')
    if (!userId) return
    let res = await uSelectUserInfo({userId})
    if (res && res.result === 'success') {
      this.pageData = res.data
    } else {
      this.pageData = {
        devCount: 0,
        user: null
      }
    }
  }

  @observable newPhone: string = ''
  @computed get getNewPhone() {
    return this.newPhone.replace(/\s/g, '')
  }
  @action.bound
  getSplitPhone(val: string) {
    val = val.replace(/\s/g, '')
    let phone = ''
    for (var i = 0; i < val.length; i++) {
      if (i == 2 || i == 6) {
        phone += val.charAt(i) + ' '
      } else {
        phone += val.charAt(i)
      }
    }
    return phone
  }
  @action.bound
  changeNewPhone(newPhone: string) {
    this.newPhone = newPhone
  }
  @action.bound
  checkPhone() {
    if (!this.getNewPhone) {
      this.desc = '请输入手机号'
      return false
    }
    if (this.getNewPhone.length < 11) {
      this.desc = '新手机号长度不足11位'
      return false
    }
    return true
  }

  @observable authCode: string = ''
  @action.bound
  changeAuthCode(authCode: string) {
    this.authCode = authCode
  }

  @observable desc: string = ''

  @action.bound
  async formSubmit(cb?: Function) {
    let userId = getStorage('userId')
    if (!userId) return
    if (!this.checkPhone()) return
    if (!this.authCode) return

    let res = await uEditUserPhone({
      userId,
      newUserPhone: this.getNewPhone,
      verfiyCode: this.authCode
    })
    if (res) {
      if (res.result === 'success') {
        Taro.showToast({
          icon: 'success',
          title: '修改成功'
        })
        this.desc = ''
      } else if (res.result === 'error' && res.msg) {
        this.desc = res.msg
      }
    }
    this.newPhone = ''
    this.authCode = ''
    this.updatePageDataSource()
    cb && cb()
  }

  @action.bound
  async getAuthCode() {
    const userId = getStorage('userId')
    if (!userId) return
    if (!this.checkPhone()) return
    let res = await verifyGetCode({userPhone: this.getNewPhone, userId})
    if (res) {
      if (res.result === 'success') {
        this.desc = '验证码发送成功'
        this.sendAuthCodeBtnClick()
        this.desc = '已发送验证码'
      } else if (res.result === 'error' && res.msg) {
        this.desc = res.msg
      }
    }
  }

  @action.bound
  clearPageData() {
    this.authCode = ''
    this.newPhone = ''
  }

  @observable seconds: number = 61
  @observable times: number = 0
  @observable timer: NodeJS.Timer | null = null

  @observable text: {
    defaultText: string
    countDownText: [string, string]
    againText: string
  } = {
    defaultText: '获取验证码',
    countDownText: ['', ' s'],
    againText: '重新获取'
  }

  @computed get isCountDownStart() {
    return this.seconds === 61
  }

  @computed get countDownText() {
    if (this.seconds < 61) {
      let [startStr, endStr] = this.text.countDownText
      return startStr + this.seconds + endStr
    }
    if (this.times > 0) return this.text.againText
    return this.text.defaultText
  }
  @action.bound
  initText({
    defaultText,
    countDownText,
    againText
  }: {
    defaultText: string
    countDownText: [string, string]
    againText: string
  }) {
    this.text.defaultText = defaultText
    this.text.countDownText = countDownText
    this.text.againText = againText
  }
  /**发送验证码或者重新获取验证码点击 */
  @action.bound
  sendAuthCodeBtnClick() {
    this.stopCountDown()
    console.log('倒计时开始')
    this.seconds = 60
    this.timer = setInterval(() => {
      if (this.seconds === 60) this.times++
      this.seconds--
      console.log('倒计时递减中', this.seconds)
      if (this.seconds === 0) {
        this.stopCountDown()
      }
    }, 1000)
  }
  /**倒计时结束 */
  @action.bound
  stopCountDown() {
    if (this.timer) {
      clearInterval(this.timer)
      this.timer = null
    }
    this.seconds = 61
    console.log('倒计时结束，重置状态', this.seconds, this.timer)
  }
  /**重置获取验证码的次数 */
  @action.bound
  resetTimes() {
    this.times = 0
  }
}
export const editUserPhoneStore = createContext(new Edituserphone())
